"""
Celery应用配置
"""

from celery import Celery
from app.config import settings

# 创建Celery应用实例
celery_app = Celery(
    "coal_stove_monitor",
    broker=settings.CELERY_BROKER_URL,
    backend=settings.CELERY_RESULT_BACKEND,
    include=[
        "app.tasks.simple_monitor_tasks",
        "app.tasks.notification_tasks",
        "app.tasks.cleanup_tasks"
    ]
)

# Celery配置
celery_app.conf.update(
    # 序列化配置
    task_serializer="json",
    accept_content=["json"],
    result_serializer="json",
    
    # 时区配置
    timezone="Asia/Shanghai",
    enable_utc=True,
    
    # 任务路由配置
    task_routes={
        "app.tasks.simple_monitor_tasks.*": {"queue": "monitor"},
        "app.tasks.notification_tasks.*": {"queue": "notification"},
        "app.tasks.cleanup_tasks.*": {"queue": "cleanup"},
        "simple_check_monitors": {"queue": "monitor"},
        "ultra_precision_monitor": {"queue": "monitor"},  # 3秒档独立任务
        "precision_monitor": {"queue": "monitor"},  # 通用精度独立任务
    },
    
    # 任务执行配置
    task_always_eager=False,  # 生产环境设为False
    task_eager_propagates=True,
    
    # 结果过期时间（1小时）
    result_expires=3600,

    # 任务结果配置
    task_ignore_result=True,  # 改为False以便设置过期时间 true 不存储执行结果
    # result_persistent=False,   # 不持久化结果，重启后清除
    # 任务重试配置
    task_acks_late=True,
    task_reject_on_worker_lost=True,
    
    # Worker配置
    worker_prefetch_multiplier=1,
    worker_max_tasks_per_child=1000,

    # Broker连接配置 (修复Celery 6.0警告)
    broker_connection_retry_on_startup=True,

    # 监控配置
    worker_send_task_events=True,
    task_send_sent_event=True,
    
    # Beat调度配置 - 优化为健康检查模式
    beat_schedule={
        # 每300秒进行监控健康检查和异常恢复（避免与独立任务冲突）
        "monitor-health-check": {
            "task": "simple_check_monitors",
            "schedule": 300.0,  # 改为300秒（5分钟），减少与独立任务的冲突
        },
        # 每5分钟检查过期监控任务
        "check-expired-monitors": {
            "task": "app.tasks.cleanup_tasks.check_expired_monitors_task",
            "schedule": 300.0,  # 5分钟
        },
        # 每小时清理过期数据
        "cleanup-expired-data": {
            "task": "app.tasks.cleanup_tasks.cleanup_expired_cache",
            "schedule": 3600.0,  # 1小时
        },
        # 每天清理过期通知记录
        "cleanup-old-notifications": {
            "task": "app.tasks.cleanup_tasks.cleanup_old_notifications",
            "schedule": 86400.0,  # 24小时
        },
    },
)

# 任务装饰器配置
def task_with_retry(**kwargs):
    """带重试机制的任务装饰器"""
    default_kwargs = {
        "bind": True,
        "autoretry_for": (Exception,),
        "retry_kwargs": {"max_retries": 3, "countdown": 60},
        "retry_backoff": True,
        "retry_jitter": True,
    }
    default_kwargs.update(kwargs)
    return celery_app.task(**default_kwargs)


# 导出Celery应用实例
__all__ = ["celery_app", "task_with_retry"]
